package com.example.content.viewmodule.main

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.example.content.REMD_ALL
import com.example.content.REMD_COLLECT
import com.example.content.REMD_FEMAIL
import com.example.content.REMD_MAN
import com.example.content.manager.GlobalMgr
import com.example.content.repository.RepositoryMgr
import com.example.content.repository.bean.*
import com.example.content.repository.files.FileConvert
import com.example.content.viewmodule.BaseFuncViewModel
import com.example.content.viewmodule.login.TokenStore
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient

/**
 * Created by zhudongao
 * Desc
 * Date 2020/9/26
 */
class CommonHomeViewModel: BaseFuncViewModel() {
    val followersData = MutableLiveData<List<UserInfo>>()
    val recommendData = MutableLiveData<Pair<Boolean, List<ProductInfo>>>(Pair(true, listOf()))
    private var startIndex = 0

    private fun getRecommend(
        pageType: Int,
        sameCity: Boolean,
        offset: Int,
        resourceType: Int,
        creationType: Int,
        isRefresh: Boolean
    ) {
        launch(
            block = {
                val recommendItem =
                    RecommendReq(offset = offset, location = "南京市")
                if (sameCity) {
                    recommendItem.same_city = 1
                } else {
                    recommendItem.same_city = 3
                }
                when (pageType) {
                    REMD_ALL -> {
                        recommendItem.gender = 3
                    }
                    REMD_MAN -> {
                        recommendItem.gender = 1
                        recommendItem.resource_type = resourceType
                        recommendItem.creation_type = creationType
                    }
                    REMD_FEMAIL -> {
                        recommendItem.gender = 2
                        recommendItem.resource_type = resourceType
                        recommendItem.creation_type = creationType
                    }
                    REMD_COLLECT -> {
                        recommendItem.gender = 3
                        recommendItem.follow = 1
                    }
                }
                val listDatas = RepositoryMgr.getRecommend(recommendItem).apiData()
                if (isRefresh) {
                    startIndex = listDatas?.size!!
                } else {
                    startIndex += listDatas?.size!!
                }
                val pair = Pair(isRefresh, listDatas)
                recommendData.postValue(pair as Pair<Boolean, List<ProductInfo>>?)
            }
        )
    }

    fun refresh(pageType: Int, resourceType: Int, creationType: Int, sameCity: Boolean) {
        Log.i("freshlistener", "start refresh.......: ")
        getRecommend(pageType, sameCity, 0, resourceType, creationType, true)
    }

    fun loadMore(pageType: Int, resourceType: Int, creationType: Int, sameCity: Boolean) {
        Log.i("freshlistener", "start load more, start: " + recommendData.value?.second?.size)
        getRecommend(
            pageType,
            sameCity,
            startIndex,
            resourceType,
            creationType,
            false
        )
    }

    fun modifyUserInfo(info: UserInfo, files: List<String>) {
        launch(
            block = {
                val req = ModifyUserInfoReq(
                    nickname = info.nickname, gender = info.gender, address = info.address,
                    signature = info.signature, avatar = info.avatar
                )
                val imageFile = files[0]
                if (imageFile.isNotBlank()) {
                    if (imageFile.startsWith("/api/")) {
                        req.user_pics = listOf(imageFile)
                    } else {
                        val images = RepositoryMgr.uploadFile(FileConvert.fileWrappers(files, null))
                        req.user_pics = listOf(images?.get(0) ?: "")
                    }
                }
                val result = RepositoryMgr.modifyUserInfo(req)
//                if (result.code == 200) {
//                    GlobalMgr.userInfo.postValue(result.apiData())
//                }
            }
        )
    }

    override fun onException() {

    }

    fun loginIM() {
        launch(
            block = {
                EMClient.getInstance().login("zda", "123456789", object : EMCallBack {
                    override fun onSuccess() {
                        Log.e("CommonHomeViewModel", "登录成功")
                    }

                    override fun onError(code: Int, error: String?) {
                        Log.e("CommonHomeViewModel", "onError  erroCode: ${code}, msg: ${error}")
                    }

                    override fun onProgress(progress: Int, status: String?) {

                    }

                })
            }
        )
    }

    fun getUserInfo() {
        launch(
            block = {
                val req = UserInfoReq(id_list = listOf(TokenStore.userId))
                val apiData = RepositoryMgr.getUserInfo(req)
                if (apiData.code == 200) {
                    followersData.postValue(apiData.apiData())
                }
            }
        )
    }
}